package com.xiangban.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.xiangban.config.WxParameterConfig;
import com.xiangban.dao.*;
import com.xiangban.exception.BizException;
import com.xiangban.feign.CommonMemberFeign;
import com.xiangban.feign.CommonPayFeign;
import com.xiangban.feign.CommonsendSmsFeign;
import com.xiangban.model.*;
import com.xiangban.model.dto.OrderDto;
import com.xiangban.model.res.ApiResult;
import com.xiangban.model.res.ApiResultCode;
import com.xiangban.model.vo.TUserTicket;
import com.xiangban.service.PayService;
import com.xiangban.util.CommonUtil;
import com.xiangban.util.WXConfigUtil;
import com.xiangban.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.xiangban.util.CommonUtil.BizEmpty;

/**
 * @Author ly
 * @date 2021/12/5 16:19
 */

@Slf4j
@Service
public class PayServiceImpl implements PayService {
    @Value("${wx.WX_APPLETS_ID}")
    private String APP_ID;
    @Value("${wx.WX_APPLETS_KEY}")
    private String APP_KEY;
    @Value("${wx.WX_MCH_ID}")
    private String MCH_ID;
    @Value("${wx.MCH_ID_SECRET}")
    private String MCH_ID_SECRET;
    @Autowired
    private CommonUtil commonUtil;
    @Autowired
    private TUserMappers tUserMappers;
    @Autowired
    private HttpServletRequest  request;
    @Autowired
    private CommonPayFeign commonPayFeign;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderWasteMapper orderWasteMapper;
    @Autowired
    private AccompanyMapper accompanyMapper;
    @Autowired
    private AccompanyWalletRecodeMapper accompanyWalletRecodeMapper;
    @Autowired
    private AccompanyWalletMapper accompanyWalletMapper;
    @Autowired
    private OrderReceivingServiceImpl orderReceivingService;
    @Autowired
    private WxParameterConfig wxParameterConfig;
    @Autowired
    private UserAccompanyMapper userAccompanyMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CommonMemberFeign commonMemberFeign;
    private static String accessId = "DAYyeQdPaX869zoUpcKl0Zu2G";
    private static String accessIdAccompany = "AfcMxdqEempG46jTLPN1hzXRt";
    private static Integer money =10000;
    @Autowired
    private CommonsendSmsFeign commonsendSmsFeign;
    @Value("${smsTemplate.AccompanySmsId}")
    private String AccompanySmsId;
    @Value("${smsTemplate.UserSmsId}")
    private String UserSmsId;
    @Transactional
    @Override
    public Object WxPay(OrderDto orderDto) {
      int   statusOne  = 1;
     OrderWaste   orderNoByWasteNumber = new OrderWaste();
        if (!BizEmpty(orderDto.getOrderNo())){

            OrderWaste orderWaste1 = new OrderWaste();
            orderWaste1.setOrderNo(orderDto.getOrderNo());
            orderWaste1.setStatus(0);
             orderNoByWasteNumber = orderWasteMapper.getOrderNoByWasteNumber(orderWaste1);
            if (!BizEmpty(orderNoByWasteNumber)){
                  statusOne = orderNoByWasteNumber.getStatus();
                if (statusOne==0){
                    throw  new BizException(ApiResultCode.PLEASE_DO_NOT_REPEAT);
                }

            }
        }
        OrderWaste orderWaste =  new OrderWaste();
        String userId = commonUtil.getUserId(request);
        Integer payType = orderDto.getPayType();
        if (payType==6){//购买高级合伙人
            //先看是不是陪诊
            UserAccompany  userAccompany = new UserAccompany();
            userAccompany.setUid(Integer.parseInt(userId));
            UserAccompany accompanyByUid = accompanyMapper.getAccompanyByUid(userAccompany);
            if (BizEmpty(accompanyByUid)){
                throw  new BizException(ApiResultCode.NOT_ACCOMPANY);
            }

            //高级陪诊合伙人的一万
            HashMap<String,String> map =  new HashMap<>();
            int i = money * 100;//转化为分
            map.put("price",i+"");
//            //获取用户openid
//            String userId = commonUtil.getUserId(request);
              TUserOpenId tUser = new TUserOpenId();
              tUser.setUid(userId);
              tUser.setAccessId(accessIdAccompany);
              TUserOpenId userInfoByUid = tUserMappers.getOpenId(tUser);
            map.put("openId",userInfoByUid.getOpenId());//openid
            map.put("accessId",accessIdAccompany);
            //根据订单号 生成 流水 账单号
            String wasteNumber = commonUtil.getWasteNumber();//流水号
            //生成订单号
            String orderNo = CommonUtil.getOrderNo();
            map.put("wasteNumber",wasteNumber);
            map.put("payType","JSAPI");//jsapi支付方式
            map.put("attach","advanced@"+accompanyByUid.getAccompanyId());//自定义参数 高级陪诊+陪诊id

            orderWaste.setWasteNumber(wasteNumber);
            orderWaste.setOrderNo(orderNo);
            orderWaste.setPayType(1);
            orderWaste.setStatus(1);
            orderWaste.setPrice(i);
            orderWaste.setType(1);
            //插入到OrderWaste表
            orderWasteMapper.insertOrderWasteInfo(orderWaste);
            //钱包记录
           //根据陪诊id 查到 钱包id
            AccompanyWallet accompanyWallet = new AccompanyWallet();
            accompanyWallet.setAccompanyId(accompanyByUid.getAccompanyId());
            AccompanyWallet moneySum = accompanyWalletMapper.getMoneySum(accompanyWallet);
            //找到钱包id后进行插入钱包记录
            AccompanyWalletRecode accompanyWalletRecode =  new AccompanyWalletRecode();
            accompanyWalletRecode.setWalletId(moneySum.getId());
            accompanyWalletRecode.setMoney(BigDecimal.valueOf(money));
            //生成高级陪诊支付流水号
            String transactionNo = commonUtil.getWasteNumber();
            accompanyWalletRecode.setTransactionNo(transactionNo);
            accompanyWalletRecode.setType(4);
            accompanyWalletRecode.setStatus(1);
            accompanyWalletRecodeMapper.insertWalletByWalletId(accompanyWalletRecode);
            log.info("==================s"+JSON.toJSONString(map));
            ApiResult<Object> objectApiResult = commonPayFeign.unifiedOrder(map);
            log.info("----------------"+JSON.toJSONString(objectApiResult));

            if (!objectApiResult.isSuccess()){
                throw new BizException(objectApiResult.getMessage());
            }
            return objectApiResult.getDataMap();

        }

        if (payType==4){
            //先看有没有支付

            //会员支付 生成流水编号
            String wasteNumber = commonUtil.getWasteNumber();//流水编号
            String orderNo = orderDto.getOrderNo();//订单编号
            OrderWaste orderWaste1 = new OrderWaste();
            orderWaste1.setOrderNo(orderNo);
            orderWaste1.setWasteNumber(wasteNumber);
            orderWaste1.setType(1);
            orderWaste1.setPrice(0);
            orderWaste1.setPayType(2);
            //
            ApiResult<Object> userInfo = commonMemberFeign.getUserInfo();
            log.info(JSON.toJSONString(userInfo));
            Map<String,Object> dataMap = (Map<String,Object>)userInfo.getDataMap();

            int flag = Integer.parseInt(dataMap.get("flag").toString());

            List<Map<String, Object>> mapList = (List<Map<String, Object>>) dataMap.get("tuserTicket");
            if (flag==1){
                log.info("sojada撒大声地加速度计萨克雷的浇洒来得快");
                 throw  new BizException(ApiResultCode.NOT_MEMBER);
             }
            int memberGradeId = Integer.parseInt(dataMap.get("memberGradeId").toString());
             if (memberGradeId==1 || memberGradeId==2){//1 银卡  2 金卡 3 铂金
                 if (mapList.size()>0){
                     log.info("我我我哦沃沃沃沃沃沃沃沃");
                     for (Map<String, Object> userTicket : mapList) {
                         TUserTicket tUserTicket1 = new TUserTicket();
                         userTicket.get("ticketNo");
                         tUserTicket1.setTicketNo(Integer.parseInt(userTicket.get("ticketNo").toString()));
                         ApiResult<Object> objectApiResult = commonMemberFeign.convertTicket(tUserTicket1);
                         log.info(JSON.toJSONString(objectApiResult));
                         String message = objectApiResult.getMessage();
                         if (message.equals("Success")){
                             break;
                         }else {
                                 orderWaste1.setStatus(1);
                                 orderWasteMapper.insertOrderWasteInfo(orderWaste1);

                             return "no";
                         }
                     }
                         orderDto.setStatus(2);
                          orderWaste1.setStatus(0);
                          orderWasteMapper.insertOrderWasteInfo(orderWaste1);
                          orderMapper.updateStatusByorderNo(orderDto);
                     return "ok";
                 }else {
                     log.info("我没券》》》》》》》》》");
                     return "no";
                 }

             }
             if (memberGradeId==3){
                 log.info("我是铂金卡-》》》》》》》》》》》");
                     orderDto.setStatus(2);
                     orderWaste1.setStatus(0);
                     orderWasteMapper.insertOrderWasteInfo(orderWaste1);
                       orderMapper.updateStatusByorderNo(orderDto);

                 return "ok";
             }




        }
        if (payType==1||payType==5){

            String orderNo = orderDto.getOrderNo();
            //根据订单编号查询订单信息
            Order order = new Order();
            order.setOrderNo(orderDto.getOrderNo());
            OrderDto orderByOrderNo = orderMapper.getOrderByOrderNo(order);
            Integer status = orderByOrderNo.getStatus();

            if (status==6||status==7){
               throw new BizException(ApiResultCode.NOT_PAY_ORDER);
            }
            HashMap<String,String> map =  new HashMap<>();
            BigDecimal money = orderByOrderNo.getMoney();
            BigDecimal multiply = money.multiply(new BigDecimal(100));
            int i = multiply.intValue();
            map.put("price",i+""); //支付金额
            //获取用户openid
            TUserOpenId tUser = new TUserOpenId();
            tUser.setUid(userId);
            tUser.setAccessId(accessId);
            if (payType==5){
                tUser.setAccessId(accessIdAccompany);
            }
            TUserOpenId openId = tUserMappers.getOpenId(tUser);
            //根据订单号 生成 流水 账单号
            String wasteNumber = commonUtil.getWasteNumber();//流水号
                map.put("wasteNumber",wasteNumber);
           map.put("accessId",accessId);
           log.info(JSON.toJSONString(openId));
           map.put("payType","JSAPI");
           map.put("attach","用户支付@pay");
            map.put("openId",openId.getOpenId());//openid
            if (payType==5){
               Map<String,Object> map1 = new HashMap<>();
                 map1.put("orderNo",orderByOrderNo.getOrderNo());
                 map1.put("accompanyId",orderByOrderNo.getAccompanyId());
                 map1.put("startLatitude",orderByOrderNo.getStartLatitude().toString());
                 map1.put("startLongitude",orderByOrderNo.getStartLongitude().toString());
                redisUtil.hmset(orderByOrderNo.getOrderNo(),map1,1000);
                map.put("attach","accompanyPay@"+orderByOrderNo.getOrderNo());//陪诊代付
                map.put("accessId",accessIdAccompany);
            }

                orderWaste.setWasteNumber(wasteNumber);
                orderWaste.setOrderNo(orderNo);
                orderWaste.setPayType(1);
                orderWaste.setStatus(1);
                orderWaste.setPrice(i);
                orderWaste.setType(1);
                //插入到OrderWaste表
                orderWasteMapper.insertOrderWasteInfo(orderWaste);
            ApiResult<Object> objectApiResult = commonPayFeign.unifiedOrder(map);
            if (!objectApiResult.isSuccess()){
                throw new BizException(objectApiResult.getMessage());
            }
            return objectApiResult.getDataMap();
        }



        return null;
    }

    /**
     * 回调通知
     * */
    @Override
    public String payBack(String resXml) {
        System.out.println("resXml******:" + resXml);

        WXConfigUtil config = null;
        try {
            config = new WXConfigUtil();
            config.setAPP_ID(APP_ID);//appid
            config.setAPP_KEY(APP_KEY);//小程序/app密钥
            config.setMCH_ID(MCH_ID);//商户号
        } catch (Exception e) {
            e.printStackTrace();
        }
        WXPay wxpay = new WXPay(config);
        String xmlBack = "";
        Map<String, String> notifyMap = null;
        try {
            notifyMap = WXPayUtil.xmlToMap(resXml);         // 调用官方SDK转换成map类型数据
//            if (wxpay.isResponseSignatureValid(notifyMap)) {//验证签名是否有效，有效则进一步处理
            if (true) {//验证签名是否有效，有效则进一步处理
                String return_code = notifyMap.get("return_code");//状态
                System.out.println("return_code******" + return_code);
                String out_trade_no = notifyMap.get("out_trade_no");//商户订单号
                if (return_code.equals("SUCCESS")) {
                    if (out_trade_no != null) {
                        // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户的订单状态从退款改成支付成功
                        // 注意特殊情况：微信服务端同样的通知可能会多次发送给商户系统，所以数据持久化之前需要检查是否已经处理过了，处理了直接返回成功标志

                        xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    } else {
                        //log.info("微信手机支付回调失败订单号:{}", out_trade_no);
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                }
                return xmlBack;
            } else {
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
                //失败的数据要不要存储？
                //log.error("手机支付回调通知签名错误");
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return xmlBack;
            }
        } catch (Exception e) {
            //log.error("手机支付回调通知失败", e);
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        return xmlBack;
    }

    //支付成功后进行处理
    @Transactional
    @Override
    public void businessProcessing(String wasteNumber, String attach) throws IOException {
        String[] split = attach.split("@");
        if (split[0].equals("accompanyPay")){
            String orderNo1 = split[1];
            Map<Object, Object> hmget = redisUtil.hmget(orderNo1);
            String orderNo2 = hmget.get("orderNo").toString();
            String accompanyId1 = hmget.get("accompanyId").toString();
            String startLongitude1 = hmget.get("startLongitude").toString();
            String startLatitude1 = hmget.get("startLatitude").toString();
            Order order1 =  new Order();
            order1.setOrderNo(orderNo2);
            OrderDto orderDto = orderMapper.getOrderByOrderNo(order1);
            //查找陪诊的加价价格
            UserAccompany userAccompany = new UserAccompany();
            userAccompany.setAccompanyId(Integer.parseInt(accompanyId1));
            UserAccompany accompanyByPid = accompanyMapper.getAccompanyByPid(userAccompany);
            //修改支付状态
            orderDto.setStatus(2);
            orderDto.setPayType(5);
            orderMapper.updateStatusByorderNo(orderDto);
            //陪诊代付
            String orderNo = orderDto.getOrderNo();//订单编号
            BigDecimal startLatitude =new BigDecimal(startLatitude1);//纬度
            BigDecimal startLongitude =new BigDecimal(startLongitude1);//经度

            BigDecimal accompanyMoney = orderDto.getAccompanyMoney();//陪诊此单分成
            BigDecimal exceed = orderDto.getExceed();//超出的价格

            Order order = new Order();
            order.setOrderNo(orderNo);
            order.setStartLongitude(startLongitude);
            order.setStartLatitude(startLatitude);
            OrderDto orderDto1 = new OrderDto();
            orderDto1.setAccompanyMoney(accompanyMoney);
            orderDto1.setExceed(exceed);
            orderReceivingService.AccompanyAddWallet(accompanyByPid,order,orderDto1);
            //给用户发送短信已接单
            //根据订单号给就诊对象发送短信
             OrderDto relationPhione = orderMapper.getRelationPhoneByOrderNo(order);
             if (!BizEmpty(relationPhione.getPhone())){
                 Map<String,Object> map = new HashMap<>();
                 ApiResult<Object> send = Send(relationPhione.getPhone(), UserSmsId, map);
                 log.info(JSONObject.toJSONString(send)+">>>>>>>>>>>>>");//发送短息
             }
        }

        if (split[0].equals("advanced")){
             //    根据流水号 去把订单支付流水状态改为已支付
                 OrderWaste orderWaste = new OrderWaste();
                 orderWaste.setWasteNumber(wasteNumber);
                 orderWaste.setStatus(0);
                 orderWasteMapper.updateStatusByWasteNumber(orderWaste);
               //  修改陪诊的身份为高级陪诊
                 UserAccompany userAccompany = new UserAccompany();
                 userAccompany.setAccompanyId(Integer.parseInt(split[1]));
                 userAccompany.setIdentity(1);
                 userAccompanyMapper.updateIdentityByAccompanyId(userAccompany);

         }
if (split[0].equals("用户支付")){

        log.info("回调通知参数:"+wasteNumber+", "+attach);
        userPay(wasteNumber);


}


    }
 public void userPay(String wasteNumber){
     //  订单状态改为预约中
     //获取订单编号
     OrderWaste orderWaste = new OrderWaste();
     orderWaste.setWasteNumber(wasteNumber);
     OrderWaste orderNoinfo =   orderWasteMapper.getOrderNoByWasteNumber(orderWaste);
     String orderNo = orderNoinfo.getOrderNo();
     //根据订单编号去改订单状态为预约中 支付状态改成支付成功
     OrderDto orderDto = new OrderDto();
     orderDto.setStatus(2);
     orderDto.setOrderNo(orderNo);
     orderDto.setPayType(1);
     orderMapper.updateStatusByorderNo(orderDto);//修改支付方式 和 支付状态
     //修改orderwaste
     orderWaste.setStatus(0);
     orderWasteMapper.updateStatusByWasteNumber(orderWaste);
     //给陪诊发送短信
     Order order = new Order();
     order.setOrderNo(orderNo);
     OrderDto orderByOrderNo = orderMapper.getAccompanyPhoneByOrderNo(order);
     if(!BizEmpty(orderByOrderNo.getPhone())){
         Map<String,Object> map = new HashMap<>();
         Send(orderByOrderNo.getPhone(),AccompanySmsId,map);
     }
 }

   public ApiResult<Object> Send(String phone,String smsTemplate,Map<String,Object> templateParam){
       if (!BizEmpty(phone)){
           log.info("=====");
           //发短信
           SmsParameterDto smsParameterDto =  new SmsParameterDto();
           smsParameterDto.setSmsTemplate(smsTemplate);
           smsParameterDto.setMobile(phone);
           smsParameterDto.setSignName("相伴医路");
           smsParameterDto.setTemplateParam(templateParam);
           log.info(JSON.toJSONString(smsParameterDto));
           log.info(commonsendSmsFeign+"");
           ApiResult<Object> objectApiResult = commonsendSmsFeign.sendSms(smsParameterDto);
           return objectApiResult;
       }
       return null;
   }
    @Override
    public String refundOrder(String orderNo,BigDecimal money) throws Exception {
        Map<String, String> data = new HashMap<>();
        BigDecimal multiply = money.multiply(new BigDecimal("100"));
        log.info(multiply+"我是钱");
        int i = multiply.intValue();
        //获取
        OrderWaste orderWaste = new OrderWaste();
        orderWaste.setStatus(0);
        orderWaste.setOrderNo(orderNo);
        OrderWaste orderIdByWasteNumber = orderWasteMapper.getOrderNoByWasteNumber(orderWaste);
        data.put("out_refund_no", commonUtil.getRefundWasteNumber());
        data.put("out_trade_no", orderIdByWasteNumber.getWasteNumber());
        data.put("total_fee", orderIdByWasteNumber.getPrice()+"");
        data.put("refund_fee",i+"");
        WXConfigUtil config = new WXConfigUtil();
        config.setAPP_ID(APP_ID);
        config.setMCH_ID(MCH_ID);
        config.setAPP_KEY(MCH_ID_SECRET);
        WXPay wxpay = new WXPay(config);
        data.put("appid",APP_ID);
        data.put("mch_id",MCH_ID);
        data.put("nonce_str",WXPayUtil.generateNonceStr());
        String s = WXPayUtil.generateSignature(data,MCH_ID_SECRET);
        data.put("sign",s);
        Map<String, String> resp = null;
        try {
            resp = wxpay.refund(data);
        } catch (Exception e) {
            e.printStackTrace();
            throw  new BizException(ApiResultCode.NO_ERRO);
        }
        if (BizEmpty(resp)){
            throw  new BizException(ApiResultCode.NO_ERRO);
        }
        System.err.println(resp);
        String return_code = resp.get("result_code");   //返回状态码
        String return_msg = resp.get("return_msg");     //返回信息

        String resultReturn = null;
        if ("SUCCESS".equals(return_code)) {
            String result_code = resp.get("result_code");       //业务结果
            String err_code_des = resp.get("err_code_des");     //错误代码描述
            if ("SUCCESS".equals(result_code)) {
                //表示退款申请接受成功，结果通过退款查询接口查询
                //修改用户订单状态为退款申请中（暂时未写）
                resultReturn = "退款申请成功";
            } else {
                log.info("订单号:{}错误信息:{}", err_code_des);
                resultReturn = err_code_des;
            }
        } else {
            log.info("订单号:{}错误信息:{}", return_msg);
            resultReturn = return_msg;
        }

        return return_code;
    }
   @Transactional
    @Override
    public Object wxDrawings(AccompanyWallet accompanyWallet) {//金额
        BigDecimal bigDecimal = new BigDecimal("200.0");
       if (accompanyWallet.getMoney().compareTo(bigDecimal)>-1){
           throw  new BizException(ApiResultCode.ASTRICT);
       }
       Pattern pattern = Pattern.compile("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
       Matcher matcher = pattern.matcher("1");
       if (!matcher.matches()){
           throw  new BizException(ApiResultCode.NOT_FIGURE);
       }
       String userId = commonUtil.getUserId(request);
        //首先看看这个陪诊账号是否 停用 还是 未认证
        UserAccompany userAccompany = new UserAccompany();
        userAccompany.setUid(Integer.parseInt(userId));
        UserAccompany accompanyByUid = accompanyMapper.getAccompanyByUid(userAccompany);
       if (BizEmpty(accompanyByUid)){
           throw new BizException(ApiResultCode.NOT_ACCOMPANY);
       }
       Integer workStatus = accompanyByUid.getWorkStatus();
       if (workStatus!=0){
           throw new BizException(ApiResultCode.FREEZE);
       }
        accompanyWallet.setAccompanyId(accompanyByUid.getAccompanyId());

       BigDecimal money = accompanyWallet.getMoney();//需要扣除的钱
       //在查看我的钱包里有多少钱
        AccompanyWallet moneySum = accompanyWalletMapper.getMoneySum(accompanyWallet);

        if ((moneySum.getMoney()).compareTo(accompanyWallet.getMoney())>-1){//钱包的钱大于提现的钱
            //余额充足
          //记录流水账单
            String wasteNumber = commonUtil.getWasteNumber();
            AccompanyWalletRecode accompanyWalletRecode = new AccompanyWalletRecode();
            accompanyWalletRecode.setWalletId(moneySum.getId());
            accompanyWalletRecode.setMoney((accompanyWallet.getMoney()).multiply(new BigDecimal("-1")));
            accompanyWalletRecode.setStatus(1);
            accompanyWalletRecode.setType(3);
            accompanyWalletRecode.setTransactionNo(wasteNumber);
            accompanyWalletRecodeMapper.insertWalletByWalletId(accompanyWalletRecode);
            //扣除钱包
            BigDecimal subtract = moneySum.getMoney().subtract(accompanyWallet.getMoney());
            accompanyWallet.setMoney(subtract);
            accompanyWalletMapper.updateMoneySubtract(accompanyWallet);
            //去提现
            TUserOpenId tUser = new TUserOpenId();
            tUser.setUid(userId);
            tUser.setAccessId(accessIdAccompany);
            TUserOpenId userInfoByUid = tUserMappers.getOpenId(tUser);
            HashMap hashMap = new HashMap();
            BigDecimal multiply = money.multiply(new BigDecimal("100"));
            int i = multiply.intValue();
            hashMap.put("accessId",accessIdAccompany);
            hashMap.put("price",i);
            hashMap.put("openId",userInfoByUid.getOpenId());
            hashMap.put("desc","薪资报酬");
            hashMap.put("wasteNumber",wasteNumber);
            ApiResult transfers = commonPayFeign.transfers(hashMap);
            Map<String, Object> dataMap = (Map<String, Object>) transfers.getDataMap();

            if(transfers.isSuccess()){
            //成功后 修改 提现状态
              accompanyWalletRecode.setStatus(0);
            accompanyWalletRecodeMapper.updateWalletByTransaction(accompanyWalletRecode);
            return "ok";
            }
            else {
                //失败后 把钱回滚 设置失败
//                accompanyWallet.setMoney(moneySum.getMoney());
//                accompanyWalletMapper.updateMoneySubtract(accompanyWallet);
                accompanyWalletRecode.setStatus(2);
                accompanyWalletRecodeMapper.updateWalletByTransaction(accompanyWalletRecode);
                return "no";

            }
        }else {
            throw new BizException(ApiResultCode.NOT_SUFFICIENT_FUNDS);
        }

    }
}
